package org.dizena.config;

import org.hibernate.validator.HibernateValidator;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.MultipartConfigElement;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

@Configuration
public class WebConfig
{

    @Bean
    public RestTemplate restTemplate()
    {

        return new RestTemplate();
    }

    /**
     * 配置Spring自动校验-规则
     */
    @Bean
    public Validator validator()
    {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure()
                //failFast的意思只要出现校验失败的情况，就立即结束校验，不再进行后续的校验。
                .failFast(true).buildValidatorFactory();
        return validatorFactory.getValidator();
    }

    /**
     * 配置Spring自动校验
     */
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor()
    {
        MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
        methodValidationPostProcessor.setValidator(validator());
        return methodValidationPostProcessor;
    }

    /**
     * 跨域请求配置
     */
    @Bean
    public WebMvcConfigurer webMvcConfigurer()
    {
        return new WebMvcConfigurer()
        {
            @Override
            public void addCorsMappings(@NotNull CorsRegistry registry)
            {
                registry
                        // 设置允许跨域的路径
                        .addMapping("/api/**")
                        // 设置允许跨域请求的域名
                        .allowedOrigins("*")
                        // 设置允许header
                        .allowedHeaders("*")
                        // 设置允许的方法
                        .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                        // 这里：是否允许证书
                        .allowCredentials(true)
                        // 跨域允许时间
                        .maxAge(3600);
            }
        };
    }


    @Bean
    public MultipartConfigElement multipartConfigElement()
    {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxRequestSize(DataSize.ofMegabytes(100));
        factory.setMaxFileSize(DataSize.ofMegabytes(100));
        return factory.createMultipartConfig();
    }

}